<template>
  <div style="padding-bottom: 30px">
    <avue-form ref="ruleForm"
               v-model="ruleForm"
               :option="option"> </avue-form>
    <el-divider></el-divider>
    <el-row style="padding-left: 30px; padding-bottom: 50px">
      <p class="font-weight node_name"
         style="font-size: 13px">
        {{ jsonDatas ? nodeName : '' }}
      </p>
      <node-form v-if="jsonDatas"
                 :jsonData="jsonDatas"
                 :formvalues="formvaluesInfo"
                 @sendmsg="getMsg"
                 ref="mychild"></node-form>
    </el-row>
    <el-row class="sequence_flows_btns button-fixed">
      <el-button class="el-button el-button--primary el-button--medium h30Btn"
                 v-for="item in sequenceFlows"
                 :key="item.id"
                 type="primary"
                 @click="changeFlows(item)">{{ item.name }}</el-button>
    </el-row>
    <!-- 转派弹框 -->
    <redeploy-dialog v-show="redeployShow"
                     v-if="forms.nodes != []"
                     :formNodes="forms.nodes"
                     @redeployShow="redeployShowFun"
                     @cancelredeployShow="cancelredeployShowFun"></redeploy-dialog>
    <!-- 短信弹窗 -->
    <note-dialog v-show="noteShow"
                 :isStartNode="true"
                 :descContent="infoData"
                 :phoneNum="itemType == '3' ? ruleForm.call_number : ruleForm.phone_number"
                 @noteShow="noteShowFn"></note-dialog>
    <!-- 邮件弹窗 -->
    <!-- <mail-dialog v-show="mailShow"
                 @mailShow="mailShowFn"></mail-dialog> -->
  </div>
</template>

<script>
import {
  bankCode,
  terminationDate,
  paidDate,
  getAddress
} from '@/api/eripDataSynController.js'
import { newOption } from '@/common/commonOption.js'
import nodeForm from '@/components/common/nodeForm'
import { getTemplateFromOfStartNode } from '@/api/workOrderTypeNode'
import { SystemField } from '@/common/generalField.js'
import {
  getWorkOrderTypeByUserId,
  getCreateNode,
  create,
  getSelectableNodes,
  getProcessMessage,
  getMsgTemplate
} from '@/api/workOrderController'
import redeployDialog from '@/views/orderDataList/orderDialog/redeployDialog'
import noteDialog from '@/views/orderDataList/orderDialog/noteDialog'
import mailDialog from '@/views/orderDataList/orderDialog/mailDialog'
export default {
  props: {
    workbenchInfo: {
      type: Object,
      default: {}
    },
    sendCreate: {
      type: Boolean,
      default: {}
    },
    typeData: {
      type: Number
    },
    customerId: {
      type: String
    },
    orderTypeName: {
      type: String
    },
    orderDetailsId: {
      type: String
    },
    isOrderCreate: {
      type: Boolean
    }
  },
  // 备注：工单分类,涉及机构,交易渠道数据暂无，暂时用source做替换
  data () {
    // 客户姓名 可输入汉字,字母,各种字符,最长可输入60个汉字,120个字符
    let name = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入客户姓名'))
      } else {
        callback()
      }
    }
    var tel = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入联系电话'))
      } else {
        callback()
      }
    }
    return {
      itemType: window.CONFIG.itemType,
      // 工作台带过来的数据
      formvalues: {
        // 'dealDate': new Date(),
        // 'userId': this.$store.state.userId
      },
      formKeySign: '0',
      classifyList: [],
      // 短信和邮件的模板数据
      infoData: {
        list: [],
        templateData: []
      },
      noteShow: false, // 短信弹窗
      mailShow: false,
      redeploy: '', //转派信息
      sizeValue: '',
      agentName: '', // 座席姓名
      exportWorkOrderIdList: '',
      redeployShow: false,
      type: [],
      jsonData: {},
      forms: {
        nodeVal: '',
        nodes: [],
        userType: '',
        userTypes: [],
        userValue: [],
        userOptions: []
      },
      ruleForm: {
        customField: {}
      },
      nodeId: '',
      nodeName: '',
      sequenceFlows: [],
      getJsonData: {},
      opration: {},
      jsonDatas: '',
      customFormInfo: '', // 客户的基本信息
      summaryInfo: {},
      oldFormvalues: '',
      workbendata: {},
      // agentInfo:'',
    }
  },
  components: {
    nodeForm,
    redeployDialog,
    noteDialog,
    mailDialog
  },
  created () {
    // this.getWorkOrderTypeByUserIdFun()
    this.exportWorkOrderIdList = this.$route.params.list
      ? this.$route.params.list.join(',')
      : ''
  },
  computed: {
    classifyShow () {
      return this.ruleForm.workOrderTypeId && this.formKeySign === '1'
    },
    // 监听用户信息
    agentInfoFun () {
      let agentInfo = JSON.parse(sessionStorage.getItem('agentInfo'))
      return agentInfo
    },
    workbenchInfos: {
      get () {
        return this.workbenchInfo
      },
      set () { }
    },
    userId () {
      return this.$store.state.userId
    },
    option () {
      let valueArray = {
        sizeValue: this.sizeValue,
        type: this.type,
        classifyList: this.classifyList
      }
      let formInfo = this.ruleForm.customField
      let formFun = {
        changeRegion: this.changeRegion,
        changeProblem: this.changeProblem,
        classifyShow: this.classifyShow
      }
      return newOption(valueArray, formInfo, formFun)
    },
    formvaluesInfo () {
      var formvaluesInfo = Object.assign(this.formvalues, this.oldFormvalues)
      return formvaluesInfo
    }
  },
  watch: {
    jsonData (n, o) {
      this.jsonDatas = n
    },
    typeData (n, o) {
      this.typeData = n
      if (this.typeData === 2) {
        this.getWorkOrderTypeByUserIdFun()
      }
    },
    workbenchInfo (n, o) {
      this.workbenchInfos = n
      this.customerId = ''
      this.getWorkOrderTypeByUserIdFun()
      // 产品的
      let infoParams = {}
      if (n.uid) {
        this.customerInfoConfMapper(n.uid)
      }
    },
    customerId (n, o) {
      this.customerId = n
      if (this.customerId) {
        this.getWorkbenchInfo()
      }
    },
  },
  mounted () {
    if (this.orderTypeName === '新建关联工单') {
      this.getProcessMessageInfo()
    } else if (this.orderTypeName !== '新建关联工单' && this.orderDetailsId) {
      this.exportWorkOrderIdList = this.orderDetailsId
    }
    if (this.$store.state.userId || sessionStorage.getItem('userIds')) {
      this.getWorkbenchInfo()
      this.getWorkOrderTypeByUserIdFun()
    }
  },
  methods: {
    // 获取客户信息
    customerInfoConfMapper (phone) {
      let params = window.CONFIG.CRMParams
      let filterValues = [
        {
          cond: 0,
          name: 'tel',
          value: phone
        },
        {
          cond: 0,
          name: 'tel1',
          value: phone
        },
        {
          cond: 0,
          name: 'tel2',
          value: phone
        },
        {
          cond: 0,
          name: 'contact_person1_tel',
          value: phone
        },
        {
          cond: 0,
          name: 'contact_person2_tel',
          value: phone
        }
      ]
      params.filters = filterValues
      let _this = this
      _this.workbendata = {}
      axios.post(window.CONFIG.CRMUrl, params).then(
        function (res) {
          if (res.data.code == 200) {
            if (res.data.data) {
              let data = res.data.data.listData[0]
              let telSign = ''
              for (var i in data) {
                if (data[i] === phone) {
                  telSign = i
                  break
                }
              }
              data['ews_phone_number'] = data[telSign]
              if (res.data.data.listData.length > 0) {
                _this.workbendata = data
              }
            }
          }
          _this.getWorkbenchInfo()
        },
        function (res) {
          console.log(res.status)
        }
      )
    },
    // 新建关联工单
    getProcessMessageInfo () {
      let params = {
        id: this.orderDetailsId,
        userId: this.$store.state.userId
      }
      getProcessMessage(params).then(res => {
        let data = res.data
        let _this = this
        if (data.retCode === 200) {
          _this.ruleForm = data.data
          let startContent = res.data.data.startNodeDto.nodeContent
          let currentContent = res.data.data.currentNodeDto.formTemplate
          if (startContent && startContent.modelValue) {
            _this.oldFormvalues = startContent.modelValue
          } else if (currentContent && currentContent.modelValue) {
            _this.oldFormvalues = currentContent.modelValue
          } else {
            _this.oldFormvalues = {}
          }
          _this.ruleForm.customField = {}
          Object.assign(_this.ruleForm, _this.ruleForm.customField)
        }
      })
    },
    // 获取问题分类
    getTemplateFromOfStartNodeFun (id) {
      getTemplateFromOfStartNode(id).then(res => {
        if (res.data.retCode === 200) {
          this.classifyList = res.data.data
        }
      })
    },
    // 拼接短信模板
    getNoteTemplate (name) {
      this.infoData.templateData = []
      for (let i = 0; i < this.infoData.list.length; i++) {
        let lableInfo = this.infoData.list[i].remark
        let valueIbnfo = this.infoData.list[i].name
        var rgTestUser = /(\{[n][a][m][e]\})/
        var rgTestId = /(\{[o][r][d][e][r][I][d]\})/
        // lableInfo = lableInfo.replace(rgTestUser, " " + name + " "); lableInfo =
        // lableInfo.replace(   rgTestId,   " " + this.$store.state.orderDetailsId + " "
        // );
        this.infoData.templateData.push({ value: valueIbnfo, label: lableInfo })
      }
    },
    // 获取短信模板
    getMsgTemplate () {
      let params = {
        classify: this.ruleForm.classify || ''
      }
      getMsgTemplate(params).then(res => {
        this.infoData.list = []
        if (res.data.retCode === 200) {
          let data = res.data.data
          let _this = this
          for (let i = 0; i < data.length; i++) {
            if (data[i].name == '自定义短信') {
              _this.infoData.list = data.filter(item => {
                return item.parent == data[i].code
              })
              _this.getNoteTemplate(_this.ruleForm.clientName || '')
              return
            }
          }
        }
      })
    },
    // 关闭邮件弹窗
    mailShowFn (e) {
      this.mailShow = e
    },
    // 关闭短信弹窗
    noteShowFn (e) {
      this.noteShow = e
    },
    // 关闭转派弹框
    cancelredeployShowFun (e) {
      this.redeployShow = e
    },
    // 关闭转派弹框
    redeployShowFun (val) {
      this.redeployShow = val.redeployShow
      this.redeploy = val
      this.submitForm('ruleForm')
    },
    // 下拉数据去重
    arrayUnique (arr, name) {
      var hash = {}
      return arr.reduce(function (item, next) {
        hash[next[name]] ? '' : (hash[next[name]] = true && item.push(next))
        return item
      }, [])
    },
    // 复制工单
    // relationOrderInfo () {
    //   if (this.$store.state.orderTitle === "新建关联工单") {
    //     let params = {
    //       id: this.$store.state.orderDetailsId,
    //       userId: this.$store.state.userId
    //     };
    //     getProcessMessage(params).then(res => {
    //       this.customFormInfo = res.data.data;
    //       this.getWorkbenchInfo();
    //     });
    //   } else {
    //     this.customFormInfo = "";
    //   }
    // },
    // 获取工作台传过来的数据
    getWorkbenchInfo () {
      if (sessionStorage.getItem('workbenchInfoFun')) {
        // call--电话、appchat --手机、 webchat-- 网页 、wechat---微信
        this.workbenchInfo = this.workbenchInfo ? this.workbenchInfo : ''
        this.ruleForm.phone = this.workbenchInfo && this.workbenchInfo.chatType === 'call' ? this.workbenchInfo.uid || '' : '' // 进线号码
        let idNumber = this.workbenchInfo.userData ? this.workbenchInfo.userData.p_cert_num : '' // 身份证号
        let workbendata = {
          customer_name: this.workbendata['customerName'] ? this.workbendata['customerName'] : this.workbenchInfo.username, // 客户姓名
          id_number: this.workbendata['idNumber'] ? this.workbendata['idNumber'] : idNumber, //身份证
          phone_number: this.workbendata['ews_phone_number'] ? this.workbendata['ews_phone_number'] : this.ruleForm.phone, // 联系电话,
          call_number: this.workbendata['ews_phone_number'] ? this.workbendata['ews_phone_number'] : this.ruleForm.phone,
        }
        this.formvalues = Object.assign(SystemField(workbendata))
      } else {
        this.workbenchInfo = this.workbenchInfos
        this.ruleForm = {}
        this.formvalues = Object.assign(SystemField({})
        )
      }
    },
    changeFlows (val) {
      this.opration = val
      if (val.type === 'zhuanpai') {
        this.redeployShow = true
      } else if (val.type === 'mail') {
        this.mailShow = true
      } else if (val.type === 'note') {
        this.noteShow = true
        this.getMsgTemplate()
      } else if (val.type === 'phone') {
        this.phoneShow = true
      } else if (val.type === 'record') {
        this.recordShow = true
      } else if (val.type === 'copy') {
        // this.$router.push('./createForm')
        this.$emit("hadleFormdetails", '新建');
      } else {
        this.submitForm('ruleForm')
      }
    },
    getMsg (data) {
      this.getJsonData = data
    },
    getCreateNode (workOrderTypeId, id) {
      let params = {
        workOrderTypeId: workOrderTypeId,
        formTemplateId: id
      }
      let _this = this
      getCreateNode(params).then(res => {
        let data = res.data
        if (data.retCode === 200) {
          _this.nodeId = data.data.nodeId
          _this.nodeName = data.data.nodeName
          _this.jsonData = data.data.formTemplate
          _this.sequenceFlows = data.data.sequenceFlows
          getSelectableNodes({
            workOrderTypeId: workOrderTypeId,
            nodeId: data.data.nodeId
          }).then(res => {
            let data = res.data
            if (data.retCode === 200) {
              _this.forms.nodes = data.data
              // 过滤当前节点
              for (var i = 0; i < _this.forms.nodes.length; i++) {
                if (data.data[i].nodeId == _this.nodeId) {
                  _this.forms.nodes.splice(i, 1)
                }
              }
            }
          })
        }
      })
    },
    changeRegion (id) {
      if (!id) {
        this.nodeId = ''
        this.nodeName = ''
        this.jsonData = ''
        this.sequenceFlows = ''
        return
      }
      this.ruleForm.classifyData = ''
      let _this = this
      for (var i in this.type) {
        if (this.type[i].id === id) {
          _this.formKeySign = this.type[i].formKeySign
        }
      }
      if (_this.formKeySign === '1') {
        this.jsonDatas = ''
        this.getTemplateFromOfStartNodeFun(id)
        return
      }
      this.getCreateNode(id, '')
    },
    getFormTemplateId (id, data, formTemplateId) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].id === id) {
          formTemplateId = data[i].formType
        } else {
          if (data[i].children && data[i].children.length > 0) {
            formTemplateId = this.getFormTemplateId(
              id,
              data[i].children,
              formTemplateId
            )
          }
        }
      }
      return formTemplateId
    },
    changeProblem (val) {
      if (!val.length > 0) {
        this.nodeId = ''
        this.nodeName = ''
        this.jsonData = ''
        this.sequenceFlows = ''
        return
      }
      let id = val[val.length - 1]
      let formTemplateId = this.getFormTemplateId(
        id,
        this.classifyList,
        formTemplateId
      )
      this.getCreateNode(this.ruleForm.workOrderTypeId, formTemplateId)
    },
    // 获取工单流程
    getWorkOrderTypeByUserIdFun () {
      let id = this.$store.state.userId || sessionStorage.getItem('userIds')
      getWorkOrderTypeByUserId(id).then(res => {
        let data = res.data
        if (data.retCode === 200) {
          this.type = data.data
        }
      })
    },
    cretaOrder (params) {
      let _this = this
      create(params).then(res => {
        if (res.data.retCode === 200) {
          window.parent.parent.postMessage(
            {
              event: 'CreateWorkOrder',
              data: {
                orderId: res.data.data
              }
            },
            '*'
          )
          _this.$message({ message: res.data.msg, type: 'success' })
          sessionStorage.removeItem('userIds')
          _this.$emit("removeTab", _this.orderTypeName);
          if (_this.$route.params.typeData || !sessionStorage.getItem('workbenchInfoFun')) {
            sessionStorage.removeItem('workbenchInfo')
            sessionStorage.setItem('workbenchInfoFun', '')
            // _this.$router.push('/orderTable/' + _this.$store.state.orderTypeId)
            _this.$store.commit('typeDataFun', 1)
          } else {
            _this.$emit('changeTypeData', 1)
            _this.$store.commit('historyPerformShowFun', '2')
            _this.$store.commit('typeDataFun', 1)
            _this.$EventBus.$emit('aMsg', '刷新列表')
            // _this.customerInfoConfMapper(customIdentify)
          }
        } else {
          _this.$message({ message: res.data.msg, type: 'error' })
        }
      })
    },
    async submitForm (formName) {
      let userIds
      let _this = this
      if (_this.$store.state.userId) {
        if (_this.$store.state.userId === 1) {
          userIds = Number(sessionStorage.getItem('userIds'))
        } else {
          userIds = _this.$store.state.userId
        }
      }
      if (!(await _this.$refs.mychild.change())) {
        return
      }
      // 处理唯一标识
      let updateCustomIdentify = ''
      if (!_this.isOrderCreate) {
        if (sessionStorage.getItem('customInfo') && JSON.parse(sessionStorage.getItem('customInfo')).customerId) {
          updateCustomIdentify = JSON.parse(sessionStorage.getItem('customInfo')).customerId
        } else if (sessionStorage.getItem('workbenchInfo') && sessionStorage.getItem('workbenchInfo') !== 'null') {
          if (JSON.parse(sessionStorage.getItem('workbenchInfo')).uid) {
            updateCustomIdentify = JSON.parse(sessionStorage.getItem('workbenchInfo')).uid
          }
        } else {
          updateCustomIdentify = ''
        }
      }
      if (_this.getJsonData && _this.getJsonData.modelValue) {
        _this.getJsonData.content.modelValue = _this.getJsonData.modelValue
      }
      let phone = _this.ruleForm.phone ? _this.ruleForm.phone : ''
      let params = {
        customIdentify: updateCustomIdentify ? updateCustomIdentify : phone,
        userId: userIds || window.Utils.cookie.readCookie('userId'), // 坐席工号
        workOrderTypeId: _this.ruleForm.workOrderTypeId || '', // 工单流程
        classifyValue: _this.ruleForm.classifyData.toString() || '', // 问题分类
        concatWorkOrderId: this.orderTypeName === '新建关联工单' ? _this.orderDetailsId : '', // 新建关联工单
        combineWorkOrderIds: _this.exportWorkOrderIdList, // 合并工单id
        voiceKeyId:
          sessionStorage.getItem('sessionId') &&
            sessionStorage.getItem('sessionId') !== 'undefined'
            ? sessionStorage.getItem('sessionId')
            : '', // 录音id标识
        writeFormTemplateInputDto: {
          content: _this.getJsonData.content,
          modelValue: _this.getJsonData.modelValue,
          nodeId: _this.nodeId,
          nodeName: _this.nodeName
        },
        opration: _this.opration,
        // 转派组装的数据
        redeploy: {
          roleType: _this.redeploy.roleType || '',
          targetNodeId: _this.redeploy.targetNodeId || '',
          value: _this.redeploy.value || []
        },
        externalWorkOrderId: ''
      }
      // 从详情页面过来的合并工单，将当前工单的id做合并处理
      if (
        _this.$route.params &&
        _this.$route.params.typeData == 4 &&
        _this.orderDetailsId
      ) {
        let combineArr = params.combineWorkOrderIds.split(',')
        combineArr.push(_this.orderDetailsId)
        params.combineWorkOrderIds = combineArr.join(',')
      }
      _this.ruleForm.customField['CREATE_AGENTID'] = _this.agentInfoFun && _this.agentInfoFun.agentId || ''
      params.customField = _this.ruleForm.customField || {};
      await _this.$refs[formName].validate(valid => {
        if (valid) {
          if (_this.opration.type === 'zhuanpai') {
            _this.cretaOrder(params, updateCustomIdentify)
          } else {
            _this.cretaOrder(params, updateCustomIdentify)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>
<style scoped>
.paging-foot {
  padding: 10px 0;
}

.el-divider--horizontal {
  margin: 20px 0;
}

.el-icon-arrow-left {
  font-size: 13px;
  color: #b60028;
  font-weight: 700;
  padding: 0 5px;
  cursor: pointer;
}

.node_name {
  margin-bottom: 10px;
}

.sequence_flows_btns {
  padding-left: 30px;
  width: 70%;
  margin: 0 auto;
}

.button-fixed {
  position: fixed;
  bottom: 0;
  width: 100%;
  left: 0;
  z-index: 10;
  background: #fff;
  text-align: right;
  padding: 15px;
}

> .el-input__icon {
  color: #2594f2;
  font-weight: bold;
}
>>> .el-col-xs-24 {
  width: 50% !important;
}
.classifyData {
  display: flex;
  margin-left: -70px;
}
>>> .avue-form__menu {
  display: none;
}
>>> .el-divider--horizontal {
  margin: 0 0 20px 0;
}
</style>